<template>
  <el-dialog :title="!dataForm.productId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible"
    @close="onClose">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
      label-width="80px">
      <el-form-item label="分类" prop="categoryId">
        <!-- <el-input v-model="dataForm.categoryId" placeholder="所属末级分类ID"></el-input> -->
        <category-cascader ref="categoryCascader" :categoryId="dataForm.categoryId" :catelogPath.sync="catelogPath"
          @getCategoryPath="getCategoryPath"></category-cascader>
        <!-- <category-cascader></category-cascader> -->
      </el-form-item>
      <el-form-item label="商品标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="商品标题（含关键属性）"></el-input>
      </el-form-item>
      <el-form-item label="商品描述" prop="description">
        <el-input v-model="dataForm.description" placeholder="商品描述"></el-input>
      </el-form-item>
      <el-form-item label="主图" prop="mainImage">
        <el-upload class="upload-demo" ref="upload" action="http://localhost:88/api/oss/upload" :show-file-list="true"
          :on-change="fileChange" :file-list="fileList" accept=".jpg,.jpeg,.png,.gif,.bmp,.pdf,.JPG,.JPEG"
          :on-success="handle_success" list-type="picture" :auto-upload="true">
          <el-button>选择文件</el-button>
        </el-upload>
      </el-form-item>
      <el-form-item label="基础定价" prop="basePrice">
        <el-input v-model="dataForm.basePrice" placeholder="基础定价（单位：元）"></el-input>
      </el-form-item>
      <el-form-item label="商品状态" prop="status">
        <!-- <el-input v-model="dataForm.status" placeholder="商品状态"></el-input> -->
        <el-select v-model="dataForm.status" placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="累计浏览" prop="viewCount">
        <el-input v-model="dataForm.viewCount" placeholder="累计浏览量" disabled></el-input>
      </el-form-item>
      <!-- <el-form-item label="创建时间" prop="createdAt">
        <el-input v-model="dataForm.createdAt" :disabled="this.dataForm.productId" placeholder="创建时间"></el-input>
      </el-form-item>
      <el-form-item label="修改时间" prop="updatedAt">
        <el-input v-model="dataForm.updatedAt" :disabled="this.dataForm.productId" placeholder="最后修改时间"></el-input>
      </el-form-item> -->
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="onClose()">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import CategoryCascader from "../common/category-cascader.vue";

export default {
  components: { CategoryCascader },
  data() {
    return {
      catelogPath: [],
      fileList: [],
      visible: false,
      dataForm: {
        productId: 0,
        categoryId: '',
        title: '',
        description: '',
        mainImage: '',
        basePrice: '',
        status: 0,
        viewCount: '',
        createdAt: '',
        updatedAt: ''
      },
      dataRule: {
        categoryId: [
          { required: true, message: '所属末级分类ID不能为空', trigger: 'blur' }
        ],
        title: [
          { required: true, message: '商品标题（含关键属性）不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '商品描述不能为空', trigger: 'blur' }
        ],
        mainImage: [
          { required: true, message: '主图URL地址不能为空', trigger: 'blur' }
        ],
        basePrice: [
          { required: true, message: '基础定价（单位：元）不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '商品状态不能为空', trigger: 'blur' }
        ],
        viewCount: [
          { required: true, message: '累计浏览量不能为空', trigger: 'blur' }
        ],
        createdAt: [
          { required: true, message: '创建时间不能为空', trigger: 'blur' }
        ],
        updatedAt: [
          { required: true, message: '最后修改时间不能为空', trigger: 'blur' }
        ]
      },
      options: [{
        value: 1,
        label: '上架'
      }, {
        value: 0,
        label: '下架'
      }],
      value: ''
    }
  },
  methods: {
    init(id) {
      console.log('init', id);

      this.dataForm.productId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.fileList = []
        if (this.dataForm.productId) {
          this.$http({
            url: this.$http.adornUrl(`/product/product/info/${this.dataForm.productId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({ data }) => {
            if (data && data.code === 200) {

              console.log('fileList', this.fileList)
              this.fileList.push({ name: data.data.mainImage, url: data.data.mainImage })

              this.dataForm.categoryId = data.data.categoryId
              this.dataForm.title = data.data.title
              this.dataForm.description = data.data.description
              this.dataForm.mainImage = data.data.mainImage
              this.dataForm.basePrice = data.data.basePrice
              this.dataForm.status = data.data.status
              this.dataForm.viewCount = data.data.viewCount
              this.dataForm.createdAt = data.data.createdAt
              this.dataForm.updatedAt = data.data.updatedAt

              // 调用子组件中的方法刷新分类路径
              this.$nextTick(() => {
                this.$refs.categoryCascader.getCategoryIds(this.dataForm.categoryId)
              })
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/product/product/${!this.dataForm.productId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'productId': this.dataForm.productId || undefined,
              'categoryId': this.dataForm.categoryId,
              'title': this.dataForm.title,
              'description': this.dataForm.description,
              'mainImage': this.dataForm.mainImage,
              'basePrice': this.dataForm.basePrice,
              'status': this.dataForm.status,
              'viewCount': this.dataForm.viewCount,
              'createdAt': this.dataForm.createdAt,
              'updatedAt': this.dataForm.updatedAt
            })
          }).then(({ data }) => {
            if (data && data.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },

    onClose() {
      this.visible = false
      this.fileList = []
    },

    // 修改显示最新图片
    fileChange(file, fileList) {
      // 这是关键一句
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
      }
    },

    // 上传成功回调
    handle_success(res) {
      console.log(res)
      this.$message.success('图片上传成功')
      // 上传成功后，将图片地址赋值给dataForm.mainImage
      this.dataForm.mainImage = res.data
    },

    // 获取分类路径
    getCategoryPath(paths) {
      console.log("子组件传递的选中分类数据", paths);

      this.dataForm.categoryId = paths[paths.length - 1]
    }
  },

  // 弹窗关闭
  onClose() {
    this.visible = false
    this.fileList = []
  },


}
</script>

<style scoped>
/*修改upload组件样式，如果不修改，会出现不友好的动画效果，*/
.upload-demo {
  display: flex;
}

.el-upload-list {
  transition: none;
}

.el-list-enter-active,
.el-list-leave-active {
  transition: none;
}

.el-list-enter,
.el-list-leave-active {
  opacity: 0;
}

.el-upload-list {
  height: 40px;
}


::v-deep .el-upload-list__item {
  transition: none !important;
}
</style>
